package cash_access;

import java.io.IOException;

import mware_lib.RemoteException;
import mware_lib.namensdienst.communication.Client;
import mware_lib.namensdienst.messages.*;

public class AccountProxy extends Account{

	private String ID;
	private Client client;
	private String host;
	private int port;
	
	public AccountProxy(String host, int port, String iD) {
		ID = iD;
		this.host = host;
		this.port = port;
		
		
		//Account erstellen und AccountProxyReferenz beim Konstruktor mitgeben
		//Client erstellen
	}
	
	@Override
	public void deposit(double amount){
		try {
			client = new Client(host, port);
			client.send(new AccReqMsg(ID, "deposit", amount));
			try {
				AccRetMsg accRet = (AccRetMsg)client.receive();
				if(accRet != null && !accRet.isErfolg()){
					if(accRet.getExcType().equals("Runtime")){
						throw new RuntimeException(accRet.getErrorText());
					}
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			client.close();
			
		} catch (IOException e) {
			throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
		}
	}
	
	@Override
	public void withdraw(double amount) throws OverdraftException{
		try {
			client = new Client(host, port);
			client.send(new AccReqMsg(ID, "withdraw", amount));
			AccRetMsg accRet = (AccRetMsg)client.receive();
			if(accRet != null && !accRet.isErfolg()){
				
				if(accRet.getExcType().equals("Overdraft")){
					throw new OverdraftException(accRet.getErrorText());
				}else if(accRet.getExcType().equals("Runtime")){
					throw new RuntimeException(accRet.getErrorText());
				}
			}
			client.close();
		} catch (IOException e) {
			throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
		} catch (ClassNotFoundException e) {
			throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
		}
	}
	
	@Override
	public double getBalance(){
		double balance = -1;
		
		try {
			client = new Client(host, port);
			client.send(new AccReqMsg(ID, "getBalance", 0));
			AccRetMsg msg = (AccRetMsg) client.receive();
			balance = msg.getBalance();
			client.close();
		} catch (IOException e) {
			throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
		} catch (ClassNotFoundException e) {
			throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
		}
		
		return balance;
	}

}
